﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using System.IO;

namespace MobileShop
{
    public partial class Login : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
                PageMap = string.Format("Login[{0}]|", this.ResolveUrl("~/Login.aspx?url=MyAccount.aspx"));
        }

        protected void btnLogin_OnClick(object sender, EventArgs e)
        {
            try
            {
                lblError.Text = "";
                lblNote.Text = "";
                View_Customers cust = View_Customers.GetCustomerByEmail(txtEmail.Text);
                if (cust.RowCount <= 0)
                {
                    lblError.Text = "Invalid email address.";
                    return;
                }

                string password = POSSystem.BLL.Utilities.CreateMD5Hash(txtPassword.Text);
                if (cust.IsColumnNull(View_Customers.ColumnNames.Password) || cust.Password != password)
                {
                    lblError.Text = "Invalid password.";
                    return;
                }

                View_Customers.SetCurrentUser(cust);

                //refresh selected items price
                string ids = "";
                BasePage.SelectedItems.Rewind();
                BasePage.SelectedItems.Filter = "";
                for (int i = 0; i < BasePage.SelectedItems.RowCount; i++)
                {
                    ids = BasePage.SelectedItems.s_ProductID + ",";
                    BasePage.SelectedItems.MoveNext();
                }

                if (ids.EndsWith(","))
                    ids = ids.Remove(ids.Length - 1);

                Products p = Products.GetProductsByIds(ids);

                BasePage.SelectedItems.Rewind();
                for (int i = 0; i < BasePage.SelectedItems.RowCount; i++)
                {
                    p.Filter = Products.ColumnNames.ID + "=" + BasePage.SelectedItems.s_ProductID;
                    if (p.RowCount > 0)
                    {
                        if (cust != null && cust.Price == CustomerType.CustomerPrice.DealerPrice)
                            BasePage.SelectedItems.s_CustomerPrice = p.s_DealerPrice;
                        else if (cust != null && cust.Price == CustomerType.CustomerPrice.PartnerPrice)
                            BasePage.SelectedItems.s_CustomerPrice = p.s_PartnerPrice;
                        else
                            BasePage.SelectedItems.s_CustomerPrice = p.s_SalePrice;
                    }
                    BasePage.SelectedItems.MoveNext();
                }

                if(string.IsNullOrEmpty(Request.QueryString["url"]))
                    Response.Redirect("MyAccount.aspx");
                else
                    Response.Redirect(Request.QueryString["url"]);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("LoginCtrl.ascx.cs", "btnLogin_Click", ex.StackTrace);
                throw ex;
            }
        }

        protected void btnForget_OnClick(object sender, EventArgs e)
        {
            try
            {
                lblError.Text = "";
                lblNote.Text = "";

                if (txtEmail.Text == "")
                {
                    lblError.Text = "Please provide a registered email.";
                    return;
                }

                Customers cust = Customers.GetCustomerByEmail(txtEmail.Text);
                if (cust.RowCount <= 0)
                {
                    lblError.Text = "Invalid email address.";
                    return;
                }

                Guid guid = Guid.NewGuid();
                string newPass = guid.ToString().Replace("-", "").Substring(0, 10);

                string tempFile = Server.MapPath("~/MailTemplates/PasswordRecovery.htm");
                string content = File.ReadAllText(tempFile);
                content = string.Format(content, newPass, cust.s_CustomerName, Branches.CurrentBranch.s_Phone);

                cust.Password = POSSystem.BLL.Utilities.CreateMD5Hash(newPass);
                cust.Save();

                POSSystem.BLL.Utilities.SendEmail(txtEmail.Text, "Password Recovery", content);
                lblNote.Text = "Reset password successfully! An email has been sent to your email.";
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("Password Recovery", ex.Message, ex.StackTrace);
                lblNote.Text = "Server too busy. Please try again.";
            }
        }
    }
}